package com.ztjava.common.tool.push;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.core.Constant;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;


@ServerEndpoint(value="/websocket/{portal}/message.ws")
public class WebSocketMessage implements Serializable{
	public static Map<String,WebSocketMessage> map = new HashMap<>();
	/**
	 * 
	 */
	private static final long serialVersionUID = 7013258133658496473L;
	private Session session; 
	private String portal;
	private Integer user_id;

	//消息群发
	public static Ret sendMessage(String content){
		for(String key:map.keySet()){
			try {
				map.get(key).session.getBasicRemote().sendText(content);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return Ret.create(Constant.RESULT, Constant.SUCCESS).set(Constant.MESSAGE,"发送成功！");
	}
	//发送指定用户
	public static Ret sendMessage(Integer user_id,String content){
		if(!map.containsKey(user_id.toString())){
			return Ret.create(Constant.RESULT, Constant.ERROR).set(Constant.MESSAGE, "用户不在线！");
		}
		try {
			map.get(user_id.toString()).session.getBasicRemote().sendText(content);
		} catch (Exception e) {
			e.printStackTrace();
			return Ret.create(Constant.RESULT, Constant.ERROR).set(Constant.MESSAGE,"发送失败！");
		}
		return Ret.create(Constant.RESULT, Constant.SUCCESS).set(Constant.MESSAGE,"发送成功！");
	}
	
	@OnOpen
	public void onOpen(@PathParam("portal")String portal,Session session, EndpointConfig config){
		this.session = session;
		this.portal = portal;
	}	
	
	@OnMessage
	public void onMessage(String message,Session session) 
			throws IOException,InterruptedException{
		if(message.startsWith("cookie:")){
			message = message.substring(7,message.length());
			String[] cookie = message.split(";");
			String sessionId = null;
			if(cookie!=null){
				String cookieName = Constant.R_PRE + portal+ "_" + AuthTool.token_name+"=";
				for(String key:cookie){
					if(key.trim().startsWith(cookieName)){
						sessionId = key.trim().replace(cookieName, "");
					}
				}
			}
			if(sessionId!=null){
				Cache cache = Redis.use();
				if(cache.exists(sessionId)){
					AuthSession authSession = cache.get(sessionId);
					this.user_id = authSession.getId();
					map.put(this.user_id.toString(), this);
				}
			}
		}
	}	
	
	//用户端断开
	@OnClose
	public void onClose(){
		map.remove(user_id+"");
	}
}
